//
//  JDUserCenterViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/4/24.
//

import UIKit

class JDUserCenterViewController: JDBaseViewController {

    var mainTableView: UITableView?
//    var dataSource = [["用户名","手机号","商讯类型","收货信息"],["我的推广提成"],["注销账号"]]
    var dataSource = [["个人头像"],["用户名","手机号"],["注销账号"]]
    
    var bottomContainerView: UIView?
    var quitButton: UIButton?
    
    var isFirstLoad: Bool = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupConfig()
        self.setupUIElements()
        self.isFirstLoad = false
        // Do any additional setup after loading the view.
    }

    func setupConfig() {
        self.setupNavigationTitle("设置")
        self.setupLeftBackItem()
        self.removeSeparatorLine()
//        self.view.downloadImage("")
    }
    
    func setupUIElements() {
        
        self.bottomContainerView = UIView()
        self.view.addSubview(self.bottomContainerView!)
        self.bottomContainerView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.height.equalTo(104)
        })
        self.bottomContainerView?.backgroundColor = .white
        
        self.quitButton = UIButton(type: .custom)
        self.bottomContainerView?.addSubview(self.quitButton!)
        self.quitButton?.snp.makeConstraints({ make in
            make.left.equalTo(self.bottomContainerView!).offset(12)
            make.right.equalTo(self.bottomContainerView!).offset(-12)
            make.centerY.equalTo(self.bottomContainerView!)
            make.height.equalTo(54)
        })
        self.quitButton?.layer.cornerRadius = 27
        self.quitButton?.backgroundColor = self.commonColor
        self.quitButton?.setTitle("退出登录", for: .normal)
        self.quitButton?.setTitleColor(.black, for: .normal)
        self.quitButton?.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        self.quitButton?.addTarget(self, action: #selector(quitAction), for: .touchUpInside)
        
        self.mainTableView = UITableView(frame: .zero, style: .grouped)
        self.view.addSubview(self.mainTableView!)
        self.mainTableView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(statusBarHeight+44)
//            make.bottom.equalTo(self.view)
            make.bottom.equalTo(self.bottomContainerView!.snp.top)
        })
        self.mainTableView?.isScrollEnabled = false
        self.mainTableView?.separatorStyle = .none
        self.mainTableView?.delegate = self
        self.mainTableView?.dataSource = self
        self.mainTableView?.register(UITableViewCell.self, forCellReuseIdentifier: "userCenterCell")
        self.mainTableView?.backgroundColor = color("#F5F6F8")
    }

    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.isFirstLoad == false {
            self.mainTableView?.reloadData()
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

    @objc func quitAction() {
        if !JDTools.checkToken() {
            return
        }
        let popupConfirmView = JDPopupConfirmView()
        popupConfirmView.confirmButtonSelected = { [weak self] in
            JDLoginModel.default.userLogout()
            UserDefaults.standard.removeObject(forKey: "loginInfo")
            self?.navigationController?.popViewController(animated: true)
            DispatchQueue.main.asyncAfter(deadline: .now()+0.2) {
                let tabbarVC = JDTools.getKeyWindows()?.rootViewController as? JDTabBarController
                tabbarVC?.selectedIndex = 0
                self?.navigationController?.popToRootViewController(animated: false)
            }
        }
        popupConfirmView.titleStr = "确定退出小尨包吗？"
        JDTools.getKeyWindows()?.rootViewController?.view.addSubview(popupConfirmView)
    }
    
}

extension JDUserCenterViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.dataSource.count
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let subList = self.dataSource[section]
        return subList.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 104
        }
        return 58
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "userCenterCell")
        
        for subView in cell?.contentView.subviews ?? [UIView]() {
            subView.removeFromSuperview()
        }
        cell?.contentView.backgroundColor = color("#F5F6F8")
        
        let containerView = UIView()
        cell?.contentView.addSubview(containerView)
        containerView.snp.makeConstraints { make in
            make.left.equalTo(cell!.contentView).offset(12)
            make.right.equalTo(cell!.contentView).offset(-12)
            make.top.bottom.equalTo(cell!.contentView)
        }
        containerView.backgroundColor = .white
        
        let cellTitle = UILabel()
        containerView.addSubview(cellTitle)
        cellTitle.snp.makeConstraints { make in
            make.left.equalTo(containerView).offset(12)
            make.centerY.equalTo(containerView)
        }
        cellTitle.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 15, weight: .medium), textColor: color("#333333"))
        cellTitle.text = self.dataSource[indexPath.section][indexPath.row]

        let arrowImgV = UIImageView()
        containerView.addSubview(arrowImgV)
        arrowImgV.snp.makeConstraints { make in
            make.right.equalTo(containerView).offset(-12)
            make.centerY.equalTo(containerView)
            make.size.equalTo(CGSize(width: 5, height: 9))
        }
        arrowImgV.image = UIImage(named: "arrow_right")?.withRenderingMode(.alwaysOriginal)
        
        if indexPath.section == 0 {
            // 头像
            let portraitImageV = UIImageView()
            containerView.addSubview(portraitImageV)
            portraitImageV.snp.makeConstraints { make in
                make.centerY.equalTo(containerView)
                make.trailing.equalTo(containerView).offset(-27)
                make.size.equalTo(CGSizeMake(64, 64))
            }
            portraitImageV.layer.cornerRadius = 32
            portraitImageV.clipsToBounds = true
            portraitImageV.downloadImage(JDLoginModel.default.headerImg ?? ".", "userPortraiPlaceholder")
            
        } else {
            
            let cellInfoLabel = UILabel()
            containerView.addSubview(cellInfoLabel)
            cellInfoLabel.snp.makeConstraints { make in
                make.right.equalTo(arrowImgV.snp.left).offset(-10)
                make.centerY.equalTo(containerView)
            }
            cellInfoLabel.labelConfig(textAlignment: .right, font: UIFont.systemFont(ofSize: 15, weight: .semibold), textColor: color("#333333"))
            if indexPath.section == 1 {
                if indexPath.row == 0 {
                    cellInfoLabel.text = JDLoginModel.default.nickname//"巴布豆早教中心"
                } else if indexPath.row == 1 {
                    cellInfoLabel.text = JDLoginModel.default.mobile?.hidePhoneNumber() //"13894887766"
                }
            }
        }
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView()
        headerView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 10)
        headerView.backgroundColor = color("#F5F6F8")
        return headerView
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let currentTitle = self.dataSource[indexPath.section][indexPath.row]
        printLog("点击:\(currentTitle)")
        
//        if indexPath.section == 0 {
//            if indexPath.row == 0 {
//                printLog("用户名")
//                let changeNicknameVC = JDChangeNicknameViewController()
//                changeNicknameVC.changeNicknameCompleted = { nickname in
//                    self.mainTableView?.reloadData()
//                }
//                self.hidesBottomBarPushViewController(changeNicknameVC)
//            } else if indexPath.row == 1 {
//                printLog("修改手机号码")
//                let changePhoneNumVC = JDChangePhoneNumViewController()
//                changePhoneNumVC.changePhoneCompleted = { newPhone in
//                    self.mainTableView?.reloadData()
//                }
//                self.hidesBottomBarPushViewController(changePhoneNumVC)
//            } else if indexPath.row == 2 {
//                printLog("商讯类型")
//                let businessNewsTypeVC = JDUserBusinessNewsTypeController()
//                self.hidesBottomBarPushViewController(businessNewsTypeVC)
//            } else if indexPath.row == 3 {
//                printLog("收货信息")
//                let addressListVC = JDAddressListViewController()
//                self.hidesBottomBarPushViewController(addressListVC)
//            }
//        } else if indexPath.section == 1 {
//          
//            if indexPath.row == 0 {
//                print("我的推广提成")
//                let commissionVC = JDMyCommissionViewController()
//                self.hidesBottomBarPushViewController(commissionVC)
//            }
//            
//        } else if indexPath.section == 2 {
//            if indexPath.row == 0 {
//                
//                if !JDTools.checkToken() {
//                    return
//                }
//                let popupConfirmView = JDPopupConfirmView()
//                popupConfirmView.confirmButtonSelected = { [weak self] in
//                    
//                    printLog("注销账号")
//                    let deleteAccountVC = JDDeleteAccountViewController()
//                    self?.hidesBottomBarPushViewController(deleteAccountVC)
//
//                }
//                popupConfirmView.titleStr = "确定注销当前账号吗？"
//                JDTools.getKeyWindows()?.rootViewController?.view.addSubview(popupConfirmView)
//            }
//        }
        
        if indexPath.section == 0 {
            print("点击头像")
            let userPortraitVC = JDUserPortraitViewController()
            self.hidesBottomBarPushViewController(userPortraitVC)

        } else if indexPath.section == 1 {
            if indexPath.row == 0 {
                printLog("用户名")
                let changeNicknameVC = JDChangeNicknameViewController()
                changeNicknameVC.changeNicknameCompleted = { nickname in
                    self.mainTableView?.reloadData()
                }
                self.hidesBottomBarPushViewController(changeNicknameVC)
            } else if indexPath.row == 1 {
                printLog("修改手机号码")
                let changePhoneNumVC = JDChangePhoneNumViewController()
                changePhoneNumVC.changePhoneCompleted = { newPhone in
                    self.mainTableView?.reloadData()
                }
                self.hidesBottomBarPushViewController(changePhoneNumVC)
            }
        } else if indexPath.section == 2 {
            if indexPath.row == 0 {
                
                if !JDTools.checkToken() {
                    return
                }
                let popupConfirmView = JDPopupConfirmView()
                popupConfirmView.confirmButtonSelected = { [weak self] in
                    
                    printLog("注销账号")
                    let deleteAccountVC = JDDeleteAccountViewController()
                    self?.hidesBottomBarPushViewController(deleteAccountVC)

                }
                popupConfirmView.titleStr = "确定注销当前账号吗？"
                JDTools.getKeyWindows()?.rootViewController?.view.addSubview(popupConfirmView)
            }
        }
        
    }
}
